<?php
// +----------------------------------------------------------------------
// | Date: 05/13/2019
// | Author: zhang
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\common\model\MarketCartModel;
use app\common\model\MarketOrderModel;
use app\common\model\PayLogModel;
use app\common\model\SpecValModel;
use app\common\model\TokenMoneyModel;
use app\common\model\WuliuModel;
use cmf\controller\RestBaseController;
use http\Exception\InvalidArgumentException;
use think\Db;

/*车品超市API*/

class GoodsController extends RestBaseController
{
    //获取分类
    public function getGoodsCate()
    {
        $pid = input('pid', 0);
        $datas = db('marketcate')->where('parent_id', $pid)->where('status', '1')->order('list_order asc')->select()->toArray();
        if (!$datas) {
            $this->error('数据为空');
        }
        foreach ($datas as &$data) {
            $data['img'] = cmf_get_image_preview_url($data['img']);
        }
        $this->success($datas);
    }

    //获取商品列表
    public function getGoods()
    {
        $param = input();
        $map = [];
        $map[] = ['status', '=', '1'];
        $map[] = ['is_del', '=', '0'];
        //分类
        if (isset($param['cid']) && !empty($param['cid'])) {
            $map[] = ['cid', '=', $param['cid']];
        }
        //关键字
        if (isset($param['keyword'])) {
            $map[] = ['title', 'like', '%' . $param['keyword'] . '%'];
        }
        $datas = db('market')->field('id,title,img,showprice')->where($map)->order('id desc')->select()->toArray();
        if (!$datas) {
            $this->error('数据为空');
        }
        foreach ($datas as &$data) {
            $data['img'] = cmf_get_image_preview_url($data['img']);
        }
        $this->success($datas);
    }

    //获取商品数据
    public function getGoodsDetail()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('参数id不正确');
        }

        //获取数据
        $data = db('market')
            ->field('id,title,banner,showprice,postage,content,address_p,address_c,spec_type_id,status')
            ->where('id', $id)
            ->where('status', 1)
            ->find();
        if (!$data || $data['status'] == 0) {
            $this->error('没有该商品');
        }

        //处理轮播图
        $bannerArr = explode('|', $data['banner']);
        foreach ($bannerArr as &$banner) {
            $banner = cmf_get_image_preview_url($banner);
        }
        $data['banner'] = $bannerArr;
        $data['content'] = htmlspecialchars_decode($data['content']);
        $this->success($data);
    }

    //获取该商品全部规格
    public function getGoodsSpec()
    {
        $spec_type_id = input('spec_type_id', 0, 'intval');
        if ($spec_type_id == 0) {
            $this->error('参数spec_type_id不正确');
        }
        $data = model('SpecVal')->getSpecList($spec_type_id);
        if ($data) {
            $this->success($data);
        } else {
            $this->error('数据为空');
        }
    }

    //获取规格价格
    public function getGoodsPrice()
    {
        //传入商品 goods_id id
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id == 0) {
            $this->error('商品id 不正确');
        }
        //传入规格依次组合 spec_str  以_链接和结尾 8_6_1_
        $spec_str = input('spec_str', '');
        if (empty($spec_str)) {
            $this->error('规格参数没有');
        }
        $data = db('market_spec')->field('stock,price,image')->where('goods_id', $goods_id)->where('spec_str', $spec_str)->find();
        if (empty($data['image'])) {
            $img = db('market')->field('img')->where('id', $goods_id)->find()['img'];
            $data['image'] = cmf_get_image_preview_url($img);
        } else {
            $data['image'] = cmf_get_image_preview_url($data['image']);
        }
        if ($data) {
            $this->success($data);
        } else {
            $this->error('数据为空');
        }
    }

    /**
     * 根据传入的订单id 生成统一订单 返回金额和统一订单id
     */
    public function orderUnified($id)
    {
        if (is_array($id)) {
            $orderid_str = implode(',', $id);
        } else {
            $orderid_str = $id;
        }
        //查询订单的支付金额
        $orderDatas = db('market_order')->where('id', 'in', "$orderid_str")->select()->toArray();
        $money = 0;
        $unifiedId = '';
        foreach ($orderDatas as $orderData) {
            $unifiedId = $orderData['unified_id'];
            $money = bcadd($money, $orderData['money'], 2);
        }
        $data['order_id'] = $orderid_str;
        $data['money'] = $money;
        $data['time'] = time();
        //如果统一订单不存在 生成统一订单
        if (empty($unifiedId)) {
            $unifiedId = Db::name('market_order_unified')->insertGetId($data);
            //更新所有子订单中的统一订单id号
            Db::name('market_order')->where('id', 'in', "$orderid_str")->setField('unified_id', $unifiedId);
        } else {
            //如果统一订单存在 ， 则更新 统一订单中的order_id字段和支付金额
            Db::name('market_order_unified')->where('id', $unifiedId)->update($data);
        }
        //返回金额和统一订单id
        $result = [];
        $result['money'] = $money;
        $result['id'] = $unifiedId;
        return $result;
    }

    /*****************************确认订单***************************************/

    //获取默认收货地址
    public function getDefaultAddr()
    {
        $uid = $this->getUserId();
        $addr = model('Address')::getDefaultAddr($uid);
        if ($addr) {
            $this->success($addr, 'ok');
        } else {
            $this->error('该用户暂无默认收货地址');
        }

    }

    /***************************** 商品直接结算 ***************************************/
    //商品界面结算 确认订单
    public function confirmOrder()
    {
        //获取商品规格和数量
        $param = input();
        $goods_id = input('goods_id', 0, 'intval');
        $spec_str = input('spec_str', 0);
        $stock = input('stock', 0, 'intval');
        if ($goods_id == 0 || $stock == 0 || $spec_str == 0) {
            $this->error('参数错误');
        }
        $specData = db('market_spec')
            ->alias('s')
            ->field('s.*,m.img,m.title,m.token_money,m.postage')
            ->where('goods_id', $goods_id)
            ->where('spec_str', $spec_str)
            ->leftJoin('jzb_market m', 's.goods_id = m.id')
            ->find();
        if ($specData['stock'] < $stock) {
            $this->error('库存不足');
        }
        $specData['stock'] = $stock;
        if (empty($specData['image'])) {
            $specData['image'] = cmf_get_image_preview_url($specData['img']);
        } else {
            $specData['image'] = cmf_get_image_preview_url($specData['image']);
        }
        unset($specData['time']);
        unset($specData['img']);
        //获取规格详情
        $specData['spec_name'] = SpecValModel::getSpecNameByIdStr($spec_str);
        //商品总金额
        $goods_money = bcmul($specData['price'], $stock, 2);
        $specData['goods_money'] = $goods_money;
        //抵扣金额 = 可使用总代币 * 抵现比例
        //可使用的总代币
        $uid = $this->getUserId();
        $goodsDaibi = $specData['token_money'] * $stock;
        $haveToken = TokenMoneyModel::getTokenMoney($uid)['sum'];
        $daibi = $goodsDaibi > $haveToken ? $haveToken : $goodsDaibi;
        //是否使用代币 默认使用
        $useDaibi = input('usedabi', 1, 'intval');
        if ($useDaibi == 1) {
            //计算代币抵现额度
            $dikou = getTokenMoneyDikou();
            $dikouMoney = bcmul($daibi, $dikou, 2);
        } else {
            $dikouMoney = 0;
        }
        $specData['dikouMoney'] = $dikouMoney;
        //最后价格 = 商品价格 + 快递费 - 抵扣
        $money = bcadd($goods_money, $specData['postage'], 2);
        $money = bcsub($money, $dikouMoney, 2);
        $specData['money'] = $money;
        $this->success($specData);
    }

    //提交订单 生成订单 减少库存
    public function submitOrder()
    {
        $param = input();
        //验证输入信息
        $rule = [
            'goods_id' => 'require|number',
            'spec_str' => 'require',
            'stock' => 'require|number',
            'usedabi' => 'require|number',
            'addressid' => 'require|number',
        ];
        $msg = [
            'goods_id.require' => '商品id不能为空',
            'goods_id.number' => '商品id格式错误',
            'spec_str.require' => '规格不能为空',
            'stock.require' => '数量不能为空',
            'stock.number' => '数量格式错误',
            'usedabi.require' => '使用代币状态不能为空',
            'usedabi.number' => '使用代币状态格式错误',
            'addressid.require' => '地址id不能为空',
            'addressid.number' => '地址id格式错误',
        ];
        $result = $this->validate($param, $rule, $msg);
        if (true !== $result) {
            $this->error($result);
        }
        $uid = $this->getUserId();
        $time = time();
        $goods_id = $param['goods_id'];
        $spec_str = $param['spec_str'];
        //生成商品订单号 18位
        $goods_order_no = date('YmdHis') . cmf_random_string(4);
        //收货地址 根据收货地址id获取收货地址详情
        $addressData = model('Address')->doGetAddress($param['addressid']);
        if (!$addressData) {
            $this->error('收货地址未查询到');
        }
        $orderData = [];
        $orderDetailsData = [];
        $orderData['uid'] = $uid;
        $orderData['goods_id'] = $goods_id;
        $orderData['goods_order_no'] = $goods_order_no;
        $orderDetailsData['spec_str'] = $spec_str;
        //获取规格详情
        $orderDetailsData['spec_name'] = SpecValModel::getSpecNameByIdStr($spec_str, $limit = '-');
        $stock = $param['stock'];
        $orderDetailsData['stock'] = $stock;
        //验证购买数量
        $specData = db('market_spec')
            ->alias('s')
            ->field('s.*,m.img,m.title,m.token_money,m.postage,m.content')
            ->where('goods_id', $goods_id)
            ->where('spec_str', $spec_str)
            ->leftJoin('jzb_market m', 's.goods_id = m.id')
            ->find();
        if ($specData['stock'] < $stock) {
            $this->error('库存不足');
        }
        //标题
        $orderDetailsData['title'] = $specData['title'];
        //展示图
        if (empty($specData['image'])) {
            $orderDetailsData['img'] = cmf_get_image_preview_url($specData['img']);
        } else {
            $orderDetailsData['img'] = cmf_get_image_preview_url($specData['image']);
        }
        //单价
        $price = $specData['price'];
        $orderDetailsData['unit_price'] = $price;
        //商品总金额
        $goods_money = bcmul($price, $stock, 2);
        $orderData['goods_money'] = $goods_money;
        //邮费
        $postage = $specData['postage'];
        $orderData['postage'] = $postage;
        //抵扣金额 = 可使用总代币 * 抵现比例
        //可使用的总代币
        $goodsDaibi = $specData['token_money'] * $stock;
        $haveToken = TokenMoneyModel::getTokenMoney($uid)['sum'];
        $daibi = $goodsDaibi > $haveToken ? $haveToken : $goodsDaibi;
        $orderData['daibi'] = $daibi;
        //是否使用代币 默认使用
        $useDaibi = input('usedabi');
        if ($useDaibi == 1) {
            //计算代币抵现额度
            $dikou = getTokenMoneyDikou();
            $dikouMoney = bcmul($daibi, $dikou, 2);
        } else {
            $dikouMoney = 0;
        }
        $orderData['daibidixian'] = $dikouMoney;
        //最后价格 = 商品价格 + 快递费 - 抵扣
        $money = bcadd($goods_money, $specData['postage'], 2);
        $money = bcsub($money, $dikouMoney, 2);
        $orderData['money'] = $money;
        $orderData['address'] = $addressData['area'];
        $orderData['address_content'] = $addressData['address'];
        $orderData['username'] = $addressData['user_name'];
        $orderData['tel'] = $addressData['mobile'];
        //留言
        $orderData['msg'] = input('msg', '');
        //产品快照
        $orderData['snapshot'] = $specData['content'];
        //下单时间
        $orderData['ordertime'] = $time;
        //生成订单表
        $orderId = Db::name('market_order')->insertGetId($orderData);
        $orderDetailsData['order_id'] = $orderId;
        //生成订单详情表
        Db::name('market_order_details')->insert($orderDetailsData);
        //更改库存
        Db::name('market_spec')
            ->where('goods_id', $param['goods_id'])
            ->where('spec_str', $param['spec_str'])
            ->dec('stock', $stock)
            ->update();
        //生成统一支付订单表 用来归并支付的订单 统一修改状态 插入订单id集合
        $unifiedData = $this->orderUnified($orderId);
        $this->success($unifiedData, 'ok');
    }

    /***************************** 购物车结算 ***************************************/
    //确认订单界面
    public function confirmCartOrder()
    {
        //购物车id号
        $cartIdArr = input('id', '');
        if (empty($cartIdArr)) {
            $this->error('你还没有选择商品');
        }
        //查询购物车数据
        $cartDatas = db('market_cart')->where('id', 'in', implode(',', $cartIdArr))->select()->toArray();
        $data = [];
        //商品可抵现代币
        $allTokenMoney = 0;
        //代币抵现额度
        $dikou = getTokenMoneyDikou();
        //计算邮费
        $postageMoney = 0;
        //商品总价格
        $goodsAllMoney = 0;
        //将提交过来的购物车进行归并处理 同一商品不同规格  归并到一个同一个订单下面
        foreach ($cartDatas as $key => $cartData) {
            $goods_id = $cartData['goods_id'];
            if (!isset($data[$goods_id])) {
                $data[$goods_id] = $goods_id;
                $postageMoney += $cartData['postage'];
            }
            $goods_money = $data[$goods_id]['goods_money'] + $cartData['price'] * $cartData['num'];
            $goods_postage = $cartData['postage'];
            $allTokenMoney += $cartData['token_money'] * $cartData['num'];
            $goodsAllMoney = bcadd($goodsAllMoney, $cartData['price'] * $cartData['num']);
            $token_money = $data[$goods_id]['token_money'] + $cartData['token_money'] * $cartData['num'];
            $daibidixian = bcmul($token_money, $dikou, 2);
            $dataitem = $data[$goods_id]['data'];
            $dataitem[] = [
                'title' => $cartData['title'],
                'img' => $cartData['img'],
                'spec_str' => $cartData['spec_str'],
                'spec_name' => SpecValModel::getSpecNameByIdStr($cartData['spec_str']),
                'price' => $cartData['price'],
                'num' => $cartData['num']
            ];
            $data[$goods_id] = [
                'goods_id' => $goods_id,
                'goods_money' => $goods_money,
                'goods_postage' => $goods_postage,
                'token_money' => $token_money,
                'daibidixian' => $daibidixian,
                'data' => $dataitem];
        }
        //代币扣除方案：查出自己所有的代币  和需要使用的代币进行对比
        //抵扣金额 = 可使用总代币 * 抵现比例
        //可使用的总代币
        $uid = $this->getUserId();
        $haveToken = TokenMoneyModel::getTokenMoney($uid)['sum'];
        $daibi = $allTokenMoney > $haveToken ? $haveToken : $allTokenMoney;
        //是否使用代币 默认使用
        $useDaibi = input('usedabi', 1, 'intval');
        if ($useDaibi == 1) {
            //计算代币抵现额度
            $dikou = getTokenMoneyDikou();
            $dikouMoney = bcmul($daibi, $dikou, 2);
        } else {
            $dikouMoney = 0;
        }
        //最后价格 = 商品价格 + 快递费 - 抵扣
        $money = bcadd($goodsAllMoney, $postageMoney, 2);
        $money = bcsub($money, $dikouMoney, 2);
        $result['dikoumoney'] = $dikouMoney;
        $result['goodsAllMoney'] = $goodsAllMoney;
        $result['postageMoney'] = $postageMoney;
        $result['money'] = $money;
        $result['data'] = $data;
        $this->success($result);
    }

    //提交购物车订单 合并付款
    public function submitCartOrder()
    {
        if (!isPost()) {
            $this->error('提交方式错误');
        }
        $param = input();
        //验证输入信息
        $rule = [
            'id' => 'require',
            'usedabi' => 'require|number',
            'addressid' => 'require|number',
        ];
        $msg = [
            'id.require' => '购物车id集合不能为空',
            'usedabi.require' => '使用代币状态不能为空',
            'usedabi.number' => '使用代币状态格式错误',
            'addressid.require' => '地址id不能为空',
            'addressid.number' => '地址id格式错误',
        ];
        $validateResult = $this->validate($param, $rule, $msg);
        if (true !== $validateResult) {
            $this->error($validateResult);
        }
        $uid = $this->getUserId();
        //购物车id号
        $cartIdArr = $param['id'];
        //查询购物车数据
        $cartDatas = db('market_cart')->where('id', 'in', implode(',', $cartIdArr))->select()->toArray();
        if (empty($cartDatas)) {
            $this->error('提交的购物车产品为空');
        }
        $data = [];
        //商品可抵现代币
        $allTokenMoney = 0;
        //代币抵现额度
        $dikou = getTokenMoneyDikou();
        //收货地址 根据收货地址id获取收货地址详情
        $addressData = model('Address')->doGetAddress($param['addressid']);
        if (!$addressData) {
            $this->error('收货地址为空');
        }
        // 启动事务
        Db::startTrans();
        try {
            //将提交过来的购物车进行归并处理 同一商品不同规格  归并到一个同一个订单下面
            foreach ($cartDatas as $key => $cartData) {
                $goods_id = $cartData['goods_id'];
                if (!isset($data[$goods_id])) {
                    $data[$goods_id] = $goods_id;
                }
                $goods_money = $data[$goods_id]['goods_money'] + $cartData['price'] * $cartData['num'];
                $goods_postage = $cartData['postage'];
                $allTokenMoney += $cartData['token_money'] * $cartData['num'];
                $token_money = $data[$goods_id]['token_money'] + $cartData['token_money'] * $cartData['num'];
                $daibidixian = bcmul($token_money, $dikou, 2);
                $dataitem = $data[$goods_id]['data'];
                $dataitem[] = [
                    'title' => $cartData['title'],
                    'img' => $cartData['img'],
                    'spec_str' => $cartData['spec_str'],
                    'spec_name' => SpecValModel::getSpecNameByIdStr($cartData['spec_str']),
                    'price' => $cartData['price'],
                    'num' => $cartData['num']
                ];
                $data[$goods_id] = [
                    'goods_id' => $goods_id,
                    'goods_money' => $goods_money,
                    'goods_postage' => $goods_postage,
                    'token_money' => $token_money,
                    'daibidixian' => $daibidixian,
                    'data' => $dataitem];
            }
            $time = time();
            //生成商品订单号 18位
            $goods_order_no = date('YmdHis') . cmf_random_string(4);
            //代币扣除方案：查出自己所有的代币  和需要使用的代币进行对比
            //抵扣金额 = 可使用总代币 * 抵现比例
            //拥有的总代币
            $haveToken = TokenMoneyModel::getTokenMoney($uid)['sum'];
            $haveDaibi = $allTokenMoney > $haveToken ? $haveToken : $allTokenMoney;
            $dikou = getTokenMoneyDikou();
            $useDaibiStatus = input('usedabi', 1, 'intval');
            //订单的id集合
            $orderIdArr = [];
            foreach ($data as $key => $orders) {
                //该子订单的代币分配
                //是否使用代币 默认使用
                if ($useDaibiStatus == 1) {
                    //计算代币抵现额度
                    $daibibili = round($orders['token_money'] / $allTokenMoney, 2);
                    $daibi = round($haveDaibi * $daibibili);
                    $daibidixian = bcmul($daibi, $dikou, 2);
                } else {
                    $daibi = 0;
                    $daibidixian = 0;
                }
                //组合子订单数据
                $goods_id = $orders['goods_id'];
                $orderData['uid'] = $uid;
                $orderData['goods_id'] = $goods_id;
                $orderData['goods_order_no'] = $goods_order_no;
                $orderData['daibi'] = $daibi;
                $orderData['daibidixian'] = $daibidixian;
                $goods_money = $orders['goods_money'];
                $orderData['goods_money'] = $goods_money;
                $postage = $orders['goods_postage'];
                $orderData['postage'] = $postage;
                //最终支付金额 = 商品 + 运费 - 代币
                $money = bcadd($goods_money, $postage, 2);
                $money = bcsub($money, $daibidixian, 2);
                $orderData['money'] = $money;
                $orderData['address'] = $addressData['area'];
                $orderData['address_content'] = $addressData['address'];
                $orderData['username'] = $addressData['user_name'];
                $orderData['tel'] = $addressData['mobile'];
                //留言
                //留言input  name=msg+goods_id
                $msg = input('msg+' . $goods_id, '');
                $orderData['msg'] = $msg;
                $orderData['snapshot'] = db('market')->find($orders['goods_id'])['content'];
                $orderData['ordertime'] = $time;
                //生成子订单
                //生成订单表
                $orderId = Db::name('market_order')->insertGetId($orderData);
                array_push($orderIdArr, $orderId);
                //遍历子订单的详情
                foreach ($orders['data'] as $item) {
                    //组合子订单的详情
                    $orderDetail = [];
                    $orderDetail['order_id'] = $orderId;
                    $orderDetail['title'] = $item['title'];
                    $orderDetail['img'] = $item['img'];
                    $spec_str = $item['spec_str'];
                    $orderDetail['spec_str'] = $spec_str;
                    $orderDetail['spec_name'] = $item['spec_name'];
                    $stock = $item['num'];
                    $orderDetail['stock'] = $stock;
                    $orderDetail['unit_price'] = $item['price'];
                    //生成订单详情表
                    Db::name('market_order_details')->insert($orderDetail);
                    //库存检测
                    $specData = Db::name('market_spec')
                        ->where('goods_id', $goods_id)
                        ->where('spec_str', $spec_str)
                        ->find();
                    if ($specData['stock'] < $stock) {
                        exception('库存不足');
                    }
                    //更改库存
                    Db::name('market_spec')
                        ->where('goods_id', $goods_id)
                        ->where('spec_str', $spec_str)
                        ->dec('stock', $stock)
                        ->update();
                    //删除购物车中对应的选中的商品
                    Db::name('market_cart')
                        ->where('uid', $uid)
                        ->where('goods_id', $goods_id)
                        ->where('spec_str', $spec_str)
                        ->delete();
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        //生成统一订单
        $unifiedData = $this->orderUnified($orderIdArr);
        $this->success($unifiedData, 'ok');
    }


    /*****************************购物车***************************************/

    //加入购物车收藏
    public function addCart()
    {
        $uid = $this->getUserId();
        //传入商品 goods_id id
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id == 0) {
            $this->error('商品id 不正确');
        }
        //传入商品 数量 num 不传为1
        $num = input('num', 1, 'intval');
        //传入规格依次组合 spec_str  以_链接和结尾 8_6_1_
        $spec_str = input('spec_str', '');
        if (empty($spec_str)) {
            $this->error('规格参数没有');
        }
        $data = [];
        //检测是否有已经加入过 有则增加数量
        $MarketCart = db('MarketCart')->where('uid', $uid)
            ->where('goods_id', $goods_id)
            ->where('spec_str', $spec_str)
            ->find();
        //检测库存是否小于收藏量
        $stock = db('market_spec')->where('goods_id', $goods_id)->where('spec_str', $spec_str)->find()['stock'];

        if ($MarketCart) {
            $num = $MarketCart['num'] + $num;
            if ($stock < $num) {
                $this->error('购物车量不可以大于库存量');
            }
            $data['num'] = $num;
            $result = db('MarketCart')->where('uid', $uid)
                ->where('goods_id', $goods_id)
                ->where('spec_str', $spec_str)
                ->update($data);

        } else {
            //查询商品该规格基本信息
            $market_spec = db('market_spec')
                ->where('goods_id', $goods_id)
                ->where('spec_str', $spec_str)
                ->find();
            //查询商品基本信息
            $market = db('market')->find($goods_id);
            $data['uid'] = $uid;
            $data['goods_id'] = $goods_id;
            $data['spec_str'] = $spec_str;
            $data['title'] = $market['title'];
            if (empty($market_spec['image'])) {
                $data['img'] = cmf_get_image_preview_url($market['img']);
            } else {
                $data['img'] = cmf_get_image_preview_url($market_spec['image']);
            }
            $data['price'] = $market_spec['price'];
            $data['num'] = $num;
            $data['token_money'] = $market['token_money'];
            $data['postage'] = $market['postage'];
            if ($stock < $num) {
                $this->error('购物车量不可以大于库存量');
            }
            $result = db('market_cart')->insert($data);
        }
        if ($result) {
            $this->success();
        } else {
            $this->error('添加失败');
        }
    }

    //查看购物车
    public function seeCart()
    {
        $uid = $this->getUserId();
        $marketDatas = db('market_cart')->where('uid', $uid)->select()->toArray();
        //数据的组合
        $idArr = [];
        foreach ($marketDatas as &$marketData) {
            //规格可视化
            $marketData['spec_str'] = SpecValModel::getSpecNameByIdStr($marketData['spec_str']);
            //封面
            $marketData['img'] = cmf_get_image_preview_url($marketData['img']);
            array_push($idArr, $marketData['id']);
        }
        $totalMoney = $this->getTotalMoney($idArr);
        $this->success(compact('totalMoney', 'marketDatas'));
    }

    //批量删除购物车
    public function delCart()
    {
        if (!isPost()) {
            $this->error('请求方式错误');
        }
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('参数错误');
        }
        if (MarketCartModel::destroy($id)) {
            $this->success('', '删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //减少购物车-1
    public function desCart()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('参数错误');
        }
        //查询该商品
        $MarketCart = MarketCartModel::get($id);
        if (!$MarketCart) {
            $this->error('购物车没有该商品');
        }
        $num = $MarketCart->num;
        if ($num <= 1) {
            $this->error('已经最小了');
        }
        $MarketCart->num = --$num;
        $MarketCart->save();
        $this->success('', 'ok');
    }

    //购物车商品+1
    public function IncCart()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('参数错误');
        }
        //没传数量 默认加1
        $num = input('num', 1, 'intval');
        //查询该商品
        $MarketCart = MarketCartModel::get($id);
        if (!$MarketCart) {
            $this->error('购物车没有该商品');
        }
        $num = $MarketCart->num + $num;
        //检测库存是否小于收藏量
        $stock = db('market_spec')->where('goods_id', $MarketCart['goods_id'])->where('spec_str', $MarketCart['spec_str'])->find()['stock'];
        if ($stock < $num) {
            $this->error('购物车量不可以大于库存量');
        }
        $MarketCart->num = $num;
        $MarketCart->save();
        $this->success('', 'ok');
    }

    //获取选中的购物车价格
    public function getSelectMoney()
    {
        //传入数组 input[]
        $idArr = input('selectGoodsId', '');
        if (empty($idArr)) {
            $this->error('参数有误');
        }
        $this->success($this->getTotalMoney($idArr), 'ok');
    }

    // $idArr 购物车的id数组 根据id组获取购物车的价格
    private function getTotalMoney($idArr = [])
    {
        $Datas = db('market_cart')->where('id', 'in', implode(',', $idArr))->select()->toArray();
        $totalMoney = 0;
        foreach ($Datas as &$data) {
            $money = bcmul($data['price'], $data['num'], 2);
            $totalMoney = bcadd($totalMoney, $money, 2);
        }
        return $totalMoney;
    }

    /*****************************付款***************************************/
    /**
     * 商品统一订单id
     * 支付方式 paytype 交易类型:0:余额,1:支付宝,2:微信支付,3:银联
     */
    public function pay()
    {
        if (!isPost()) {
            $this->error('请求类型错误');
        }
        $param = input();
        $rule = [
            'id' => 'require|number',
            'paytype' => 'require|number'
        ];
        $msg = [
            'id.require' => '订单id不能为空',
            'id.number' => '订单id只能是数字',
            'paytype.require' => '支付方式不能为空',
            'paytype.number' => '支付方式只能是数字'
        ];

        $validate = $this->validate($param, $rule, $msg);
        if (true !== $validate) {
            $this->error($validate);
        }

        $id = $param['id'];
        //订单支付方式
        $pay_type = $param['paytype'];

        //获取用户id
        $uid = $this->getUserId();
        //统一订单信息
        $unifiedData = db('market_order_unified')->find($id);
        if (!$unifiedData) {
            $this->error('没有该订单');
        }
        //查询订单下面的子订单的代币总数，防止恶意刷代币
        $orderDaibi = db('market_order')->where('id', 'in', $unifiedData['order_id'])->sum('daibi');
        $havedaibi = TokenMoneyModel::getUseTokenMoney($uid);
        if ($havedaibi < $orderDaibi) {
            $this->error('您的代币数量和下单时使用的不一致，请取消订单重新创建订单');
        }
        //最终支付额度
        $money = $unifiedData['money'];
        //如果是余额支付 最终支付的钱不能大于钱包
        if ($pay_type == 0) {
            $balance = db('user')->find($uid)['balance'];
            if ($balance < $money) {
                $this->error('余额不足，请选择其他支付方式');
            }
        }
        $out_trade_no = cmf_get_order_sn();
        //更新统一订单数据
        db('market_order_unified')->where('id', $id)->update(['order_no' => $out_trade_no, 'pay_type' => $pay_type, 'time' => time()]);
        //插入订单库 项目类型 0 充值 1 商品订单 2 物流支付
        PayLogModel::setPayLog($out_trade_no, $uid, 1, $id, $money, $pay_type);
        //根据不同的订单类型  返回不同的内容  交易类型:0:余额,1:支付宝,2:微信支付,3:银联
        $orderData = '';
        switch ($pay_type) {
            case 0:
                $orderData = $this->yuePay($out_trade_no, $balance, $money);
                break;
            case 1:
                //$orderData = $this->aliPay($out_trade_no);
                $orderData = model('PayModel')->getPayinfo($pay_type = 'alipay', $pay_sn = $out_trade_no, $money, $subject = "");
                break;
            case 2:
                //$orderData = $this->weChatPay($out_trade_no);
                $orderData = model('PayModel')->getPayinfo($pay_type = 'wxpay', $pay_sn = $out_trade_no, $money, $subject = "");
                break;
            case 3:
                $orderData = $this->chinaPay($out_trade_no);
                break;
            default:
                $this->error('订单类型错误');
                break;
        }
        $this->success($orderData, 'ok');
    }

    /**
     * 余额支付
     * $out_trade_no 支付订单号
     */
    private function yuePay($order_no, $balance, $money)
    {
        $data['balance'] = $balance;
        $data['havebalance'] = bcsub($balance, $money, 2);
        $data['money'] = $money;
        $data['order_no'] = $order_no;
        return $data;
    }


    /*****************************  我的订单 ***************************************/

    //获取我的订单列表
    public function getMyOrder()
    {
        $uid = $this->getUserId();
        $map = [];
        $map[] = ['uid', '=', $uid];
        $status = input('status', '', 'intval');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $orderDatas = MarketOrderModel::where($map)->field('id,money,status,ordertime')->paginate();
        foreach ($orderDatas as &$orderData) {
            $orderData->getOrderDetails;
            $total = $orderData->getOrderDetails()->sum('stock');
            $orderData['ordertime'] = date('Y-m-d H:i', $orderData['ordertime']);
            $orderData['totalnum'] = $total;
        }
        $this->success($orderDatas, 'ok');
    }

    //待付款 立即付款
    public function submitMyOrder()
    {
        $orderId = input('id', 0, 'intval');
        if ($orderId == 0) {
            $this->error('订单id错误');
        }
        $unifiedData = $this->orderUnified($orderId);
        $this->success($unifiedData, 'ok');
    }

    //查看订单详情
    public function seeOrder()
    {
        $uid = $this->getUserId();
        $map = [];
        $map[] = ['uid', '=', $uid];
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('订单id错误');
        }
        $map[] = ['id', '=', $id];
        $orderData = MarketOrderModel::where($map)->find();
        $orderData->getOrderDetails;
        $total = $orderData->getOrderDetails()->sum('stock');
        $orderData['ordertime'] = date('Y-m-d H:i', $orderData['ordertime']);
        $orderData['totalnum'] = $total;
        $this->success($orderData, 'ok');
    }

    //获取 取消原因 退款原因 以及客服集合
    public function getOption()
    {
        $type = input('type', '');
        $result = cmf_get_option($type);
        if ($result) {
            $this->success($result);
        } else {
            $this->error('没有该类型');
        }
    }

    //查看物流信息
    public function seePost()
    {
        $orderid = input('id', 0, 'intval');
        if ($orderid == 0) {
            $this->error('订单id错误');
        }
        //订单基本信息
        $orderData = db('market_order')->field('goods_order_no,postname,postno')->find($orderid);
        //找详情中的一个的图片
        $img = db('market_order_details')->where('order_id', $orderid)->find()['img'];
        $data = [];
        $data['img'] = $img;
        $data['goods_order_no'] = $orderData['goods_order_no'];
        $data['postname'] = $orderData['postname'];
        $data['postno'] = $orderData['postno'];
        $postname = $orderData['postname'];
        $postno = $orderData['postno'];
        $postData = db('post')->where('postname', 'like', "%{$postname}%")->find();
        if (!$postData) {
            $this->error('没有查询到快递公司');
        }
        $postcode = $postData['postcode'];
        include_once '../vendor/post/post.php';
        $result = \post::index($postcode, $postno);
        $result = json_decode($result, true);
        if (true === $result['Success']) {
            $data['postData'] = $result['Traces'];
        } else {
            $data['postData'] = '空';
        }
        $this->success($data);
    }


    //确认收货
    public function confirmGetOrder()
    {
        $uid = $this->getUserId();
        $orderid = input('id', 0, 'intval');
        if ($orderid == 0) {
            $this->error('订单id类型错误');
        }
        //更改订单状态和确认时间
        Db::name('market_order')->where('id', $orderid)->where('uid', $uid)->update(['status' => 3, 'confirmtime' => time()]);
        $this->success('收货成功');
    }

    //评价商品界面
    public function comment()
    {
        $orderid = input('id');
        $detailsData = db('market_order_details')->where('order_id', $orderid)->find();
        $data['title'] = $detailsData['title'];
        $data['img'] = $detailsData['img'];
        $data['order_id'] = $orderid;
        $data['goods_id'] = db('market_order')->find($orderid)['goods_id'];
        $this->success($data);
    }

    //确认评论
    public function postComment()
    {
        $uid = $this->getUserId();
        if (!isPost()) {
            $this->error('请求类型错误');
        }
        $param = input();
        $rule = [
            'goods_id' => 'require|number',
            'order_id' => 'require|number',
            'msg' => 'require'
        ];
        $msg = [
            'goods_id.require' => 'goods_id必须',
            'goods_id.number' => 'goods_id只能是数字',
            'order_id.require' => 'order_id必须',
            'order_id.number' => 'order_id只能是数字',
            'msg.require' => '既然评论，写点东西吧。',

        ];
        $validate = $this->validate($param, $rule, $msg);
        if (true !== $validate) {
            $this->error($validate);
        }
        $goods_id = $param['goods_id'];
        $order_id = $param['order_id'];
        $msg = htmlspecialchars($param['msg']);
        $img = input('img', '');
        $status = db('market_order')->where('id', $order_id)->find()['status'];
        if ($status != 3) {
            $this->error('状态不允许');
        }
        //写入评论
        db('market_comment')->insert([
            'goods_id' => $goods_id,
            'order_id' => $order_id,
            'uid' => $uid,
            'msg' => $msg,
            'img' => $img,
            'time' => time()
        ]);

        //更新状态已完成 4
        db('market_order')->where('id', $order_id)->setField('status', 4);
        $this->success('评论成功');
    }

    //获取某个商品的评价
    public function getCommentList()
    {
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id == 0) {
            $this->error('商品id错误');
        }
        $datas = model('MarketComment')->getComment($goods_id)->toArray();
        foreach ($datas['data'] as &$data) {
            //处理图片
            if (!empty($data['img'])) {
                $data['img'] = explode('|', $data['img']);
            }
            $data['time'] = date('Y-m-d H:i:s', $data['time']);
            $data['msg'] = htmlspecialchars_decode($data['time']);
        }
        $this->success($datas);
    }

    /************************** 取消及退款 **********************************/
    //取消订单 返还商品数量
    public function cancelOrder()
    {
        if (!isPost()) {
            $this->error('请求方式错误');
        }
        $orderid = input('id', 0, 'intval');
        $reason = input('reason', '');
        if ($orderid == 0) {
            $this->error('参数错误');
        }
        if (empty($reason)) {
            $this->error('请选择取消原因');
        }
        $uid = $this->getUserId();
        //查询订单数据
        $orderData = db('market_order')->where('id', $orderid)->where('uid', $uid)->find();
        if ($orderData['status'] != 0) {
            $this->error('当前操作状态不允许');
        }
        //新增取消数据
        $oid = $orderid;
        $oldstatus = $orderData['status'];
        $backtype = 0; //申请方式 【0、取消订单 1、申请退款 3、退款不退货  5、退货退款】
        $status = $backtype;
        $backid = $this->marketorderBack($oid, $oldstatus, $backtype, $reason, $money = 0, $msg = '', $img = '', $status);
        //退回商品表的库存
        $this->backSpec($orderid);
        //更改订单状态
        /*
        订单状态（
          0、已下单待支付、
          1、已支付待发货、
          2、已发货待收货、
          3、已收货、待评价、
          4、订单完成、
          5、订单取消 恢复库存、订单自已取消 用户自己操作
          6、申请退款
          7、订单关闭						  ）
        */
        $result = db('market_order')->where('id', $orderid)->update(['status' => 5, 'backid' => $backid]);
        if ($result) {
            $this->success('');
        } else {
            $this->error('操作失败');
        }
    }

    //退款退货列表
    public function getMyBackOrder()
    {
        //全部 订单状态为6 7
        //处理中 订单状态为6
        $uid = $this->getUserId();
        $map = [];
        $map[] = ['uid', '=', $uid];
        $status = input('orderstatus', '', 'intval');
        if (empty($status)) {
            $this->error('状态错误');
        }
        if (!empty($status)) {
            $map[] = ['o.status', 'in', $status];
        }
        $orderDatas = MarketOrderModel::where($map)
            ->alias('o')
            ->field('o.id,o.money paymoney,b.time,b.status bstatus,b.money backmoney')
            ->leftJoin('jzb_marketorder_back b', 'o.backid=b.id')
            ->paginate();
        foreach ($orderDatas as &$orderData) {
            $orderData->getOrderDetails;
            $orderData['time'] = date('Y-y-m-d H:i', $orderData['time']);
        }
        $this->success($orderDatas, 'ok');
    }

    //待发货 申请退款  需要后台确认  退还写入的金额以及代币 和库存 关闭订单
    public function sendBeforeBack()
    {
        if (!isPost()) {
            $this->error('请求方式错误');
        }
        $orderid = input('id', 0, 'intval');
        $reason = input('reason', '');
        if ($orderid == 0) {
            $this->error('参数错误');
        }
        if (empty($reason)) {
            $this->error('请选择退还原因');
        }
        $uid = $this->getUserId();
        $orderData = db('market_order')->where('id', $orderid)->where('uid', $uid)->find();
        if ($orderData['status'] != 1) {
            $this->error('当前操作状态不允许');
        }
        //新增取消数据
        $oid = $orderid;
        $oldstatus = $orderData['status'];
        $backtype = 1; //申请方式 1、申请退款
        $status = $backtype;
        $money = input('money', '0', 'intval');
        if ($money > $orderData['money']) {
            $this->error('申请金额不能大于支付金额');
        }
        $msg = input('msg', '');
        $img = input('img', '');
        $backid = $this->marketorderBack($oid, $oldstatus, $backtype, $reason, $money, $msg, $img, $status);
        $result = db('market_order')->where('id', $orderid)->update(['status' => 6, 'backid' => $backid]);
        if ($result) {
            $this->success('申请成功,请等待后台处理');
        } else {
            $this->error('操作失败');
        }
    }

    //退款退货 - 仅退款
    public function onlyBackMoney()
    {
        if (!isPost()) {
            $this->error('请求方式错误');
        }
        $orderid = input('id', 0, 'intval');
        $reason = input('reason', '');
        if ($orderid == 0) {
            $this->error('参数错误');
        }
        if (empty($reason)) {
            $this->error('请选择退还原因');
        }
        $uid = $this->getUserId();
        $orderData = db('market_order')->where('id', $orderid)->where('uid', $uid)->find();
        if ($orderData['status'] != 3) {
            $this->error('当前操作状态不允许');
        }
        //新增取消数据
        $oid = $orderid;
        $oldstatus = $orderData['status'];
        $backtype = 2; //申请方式 2、收货后，申请退款不退货
        $status = $backtype;
        $money = input('money', '0', 'intval');
        if ($money > $orderData['money']) {
            $this->error('申请金额不能大于支付金额');
        }
        $msg = input('msg', '');
        $img = input('img', '');
        $backid = $this->marketorderBack($oid, $oldstatus, $backtype, $reason, $money, $msg, $img, $status);
        $result = db('market_order')->where('id', $orderid)->update(['status' => 6, 'backid' => $backid]);
        if ($result) {
            $this->success('申请成功,请等待后台处理');
        } else {
            $this->error('操作失败');
        }

    }

    //退款退货 - 退款退货
    public function backMoneyGoods()
    {
        if (!isPost()) {
            $this->error('请求方式错误');
        }
        $orderid = input('id', 0, 'intval');
        $reason = input('reason', '');
        if ($orderid == 0) {
            $this->error('参数错误');
        }
        if (empty($reason)) {
            $this->error('请选择退还原因');
        }
        $uid = $this->getUserId();

        //查询订单数据
        $orderData = db('market_order')->where('id', $orderid)->where('uid', $uid)->find();
        if ($orderData['status'] != 3) {
            $this->error('当前操作状态不允许');
        }
        //新增取消数据
        $oid = $orderid;
        $oldstatus = $orderData['status'];
        $backtype = 3; //申请方式  3、退货退款 申请中
        $status = $backtype;
        $money = input('money', '0', 'intval');
        if ($money > $orderData['money']) {
            $this->error('申请金额不能大于支付金额');
        }
        $msg = input('msg', '');
        $img = input('img', '');
        $backid = $this->marketorderBack($oid, $oldstatus, $backtype, $reason, $money, $msg, $img, $status);
        $result = db('market_order')->where('id', $orderid)->update(['status' => 6, 'backid' => $backid]);
        if ($result) {
            $this->success('申请成功,请等待后台处理');
        } else {
            $this->error('操作失败');
        }
    }

    //填写退货信息
    public function writeBackMoneyGoods()
    {
        $uid = $this->getUserId();
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('订单类型错误');
        }
        $postname = input('postname', '');
        $postno = input('postno', '');
        if (empty($postname) || empty($postno)) {
            $this->error('物流信息不能为空');
        }
        $orderData = db('market_order')->where('id', $id)->where('uid', $uid)->find();
        if ($orderData['status'] != 6) {
            $this->error('改状态不允许操作');
        }
        $backid = $orderData['backid'];
        //更新退款表   更改状态为已发货状态  填写物流信息
        $reulst = db('marketorder_back')->where('id', $backid)->update(['status' => 5, 'postname' => $postname, 'postno' => $postno]);
        if ($reulst) {
            $this->success('', '操作成功，请等待处理');
        } else {
            $this->error('系统错误');
        }
    }


    /**
     * 根据订单id 退回该订单下的所有商品表的库存
     * $orderid 订单id
     */
    protected function backSpec($orderid)
    {
        $goods_id = db('market_order')->find($orderid)['goods_id'];
        $detailsDatas = db('market_order_details')->where('order_id', $orderid)->select();
        foreach ($detailsDatas as $detailsData) {
            $spec_str = $detailsData['spec_str'];
            $stock = $detailsData['stock'];
            Db::name('market_spec')
                ->where('goods_id', $goods_id)
                ->where('spec_str', $spec_str)
                ->setInc('stock', $stock);
        }
        return true;
    }

    /**
     * 新增取消订单或退款数据
     * status 退款表状态:
     * 1、待发货，申请退款 //退还写入的金额以及订单使用的代币 和 库存 关闭订单 更改退款表状态6
     * 2、收货后，申请退款不退货  //退还写入的金额以及订单使用的代币和 关闭订单 更改退款表状态6
     * 3、退货退款 申请中 3  //更改退款状态表为4
     * 4、退货退款 申请通过 后台同意 //前台发货  更改退款状态表为5
     * 5、退货退款 后台同意之后 前台填写快递信息  //退还写入的金额以及订单使用的代币 和关闭订单 更改退款表状态为6
     * 6、完成退款
     */
    protected function marketorderBack($oid, $oldstatus, $backtype, $reason, $money = 0, $msg = '', $img = '', $status)
    {
        $data = [];
        $data['oid'] = $oid;
        $data['oldstatus'] = $oldstatus;
        $data['backtype'] = $backtype;
        $data['reason'] = $reason;
        $data['money'] = $money;
        $data['msg'] = $msg;
        $data['img'] = $img;
        $data['status'] = $status;
        $data['time'] = time();
        $backid = Db::name('marketorder_back')->insertGetId($data);
        return $backid;
    }

    /**
     * 首页推荐专区车品超市栏位
     * 展示3个
     */
    public function indexGoods()
    {
        $goodsDatas = db('market')
            ->field('id,title,img,showprice,address_p,address_c')
            ->where('status', '1')
            ->where('is_del', '0')
            ->order('is_tuijian desc,list_orders asc,id desc')
            ->limit(0, 3)
            ->select()
            ->toArray();
        foreach ($goodsDatas as &$goodsData) {
            $goodsData['img'] = cmf_get_image_preview_url($goodsData['img']);
        }
        $this->success($goodsDatas);
    }

}
